package com.hex.liyue.launchdatemodule.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hex.liyue.R;
import com.hex.liyue.commonmodule.activity.BaseActivity;
import com.hex.liyue.commonmodule.manager.UserManager;
import com.hex.liyue.commonmodule.utils.ImageUtils;
import com.hex.liyue.commonmodule.utils.L;
import com.hex.liyue.commonmodule.utils.SPUtil;
import com.hex.liyue.commonmodule.utils.StatusBarCompatUtils;
import com.hex.liyue.commonmodule.utils.Util;
import com.hex.liyue.commonmodule.view.IosChoiceDialog;
import com.hex.liyue.commonmodule.view.recycleview.YRecycleview;
import com.hex.liyue.launchdatemodule.adapter.AdapterLaunch;
import com.hex.liyue.launchdatemodule.bean.LaunchListResultBean;
import com.hex.liyue.launchdatemodule.presenter.ILaunchListView;
import com.hex.liyue.launchdatemodule.presenter.LaunchListPresenter;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 我发起约会的列表
 * Created by WJ on 2016/6/13.
 */
public class LaunchListActivity extends BaseActivity implements AdapterLaunch.OnItemClickListener, ILaunchListView, YRecycleview.RefreshAndLoadMoreListener {
    @Bind(R.id.iv_toobar_back)
    ImageView ivToobarBack;
    @Bind(R.id.tv_toobar_title)
    TextView tvToobarTitle;
    @Bind(R.id.rv_launch_list)
    YRecycleview rvLaunchList;
    @Bind(R.id.empty_launch)
    LinearLayout emptyLaunch;
    private LaunchListPresenter launchListPresenter;
    private int page = 1;
    private int pagenum = 10;
    private List<LaunchListResultBean.DataBean> list = new ArrayList<>();
    private AdapterLaunch adapterLaunch;
    private String flag = "";
    private IWXAPI wxApi;
    private boolean isShare;
    private String event;
    public static String appointmentId;

    @Override
    protected void bindPresenter() {
        launchListPresenter = new LaunchListPresenter(this);
    }

    @Override
    protected void initData(Bundle extras) {
        launchListPresenter.getLaunchList(page, pagenum);
        rvLaunchList.setRefreshAndLoadMoreListener(this);
        flag = getIntent().getStringExtra("flag");
        event = getIntent().getStringExtra("event");
        isShare = getIntent().getBooleanExtra("isShare", false);

        wxApi = WXAPIFactory.createWXAPI(this, "wxbd7b91a516360a2a");
        wxApi.registerApp("wxbd7b91a516360a2a");
        if (isShare) {
            wechatShare(1);//分享到微信朋友圈
        }
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_launch_list;
    }

    @Override
    protected void initToolbar() {
        StatusBarCompatUtils.compat(this);
        tvToobarTitle.setText("我发起的约会");
        ivToobarBack.setVisibility(View.VISIBLE);
    }


    @OnClick({R.id.iv_toobar_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_toobar_back:
                onBackPressed();
                break;
        }
    }

    /**
     * 微信分享 （这里仅提供一个分享网页的示例，其它请参看官网示例代码）
     *
     * @param flag (0:分享到微信好友，1：分享到微信朋友圈)
     */
    private void wechatShare(final int flag) {

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = "http://www.liyue888.com/index.php/Home/Share/index?appointment_id=" + appointmentId;
        final WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = "我只是想" + event + "，你咋给我送这么多礼物呢？";
        msg.description = "这里填写内容";
        // 这里替换一张自己工程里的图片资源

        BitmapDrawable bmpDraw = (BitmapDrawable) getResources().getDrawable(
                R.drawable.share_icon);
        final Bitmap thumb = bmpDraw.getBitmap();
        if (TextUtils.isEmpty(UserManager.getUserAvator())) {
            msg.setThumbImage(thumb);
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = msg;
            req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession
                    : SendMessageToWX.Req.WXSceneTimeline;
            wxApi.sendReq(req);
            return;
        }
        showLod("分享中");
        ImageUtils.getBitmap(UserManager.getUserAvator(), new ImageUtils.ResponseListener() {
            @Override
            public void onSuccess(Bitmap bitmap) {
                Bitmap bitmap2 = ImageUtils.cQuality(bitmap);
                Bitmap bitmap3 = ImageUtils.zoomImage(bitmap2, 30, 30);
                Bitmap bitmap1 = Bitmap.createScaledBitmap(bitmap3, 30, 30, true);
                msg.thumbData = Util.bmpToByteArray(bitmap1, true);
//                bitmap1.recycle();
                //  msg.setThumbImage(bitmap1);
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = msg;
                req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession
                        : SendMessageToWX.Req.WXSceneTimeline;
                wxApi.sendReq(req);

                closeLod();
            }

            @Override
            public void onError() {
                closeLod();
                msg.setThumbImage(thumb);
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = msg;
                req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession
                        : SendMessageToWX.Req.WXSceneTimeline;
                wxApi.sendReq(req);
            }
        });
    }

    @Override
    public void onItemClickListener(String appointment_id) {
        Intent intent = new Intent(this, LaunchDetailsActivity.class);
        intent.putExtra("appointment_id", appointment_id);
        startActivityForResult(intent, 0);
    }

    @Override
    public void onLongClickListener(final AdapterLaunch.MyHolder myHolder, final String appointment_id) {
        if (myHolder.canCencal) {
            //删除约会
            IosChoiceDialog iosChoiceDialog = new IosChoiceDialog(this, "系统消息", "确认取消本次约会？");
            iosChoiceDialog.setOnButtonClickListener(new IosChoiceDialog.OnButtonClickListener() {
                @Override
                public void onOkClickListener() {
                    launchListPresenter.cancelAppointment(myHolder, appointment_id);
                }

                @Override
                public void onCancelClickListener() {

                }
            });
            iosChoiceDialog.show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0) {
            page = 1;
            launchListPresenter.getLaunchList(page, pagenum);
        }
    }

    @Override
    public void showLod(String msg) {
        showLoad(this, msg);
    }

    @Override
    public void closeLod() {
        closeLoad();
    }

    @Override
    public void showT(String msg) {
        showToast(this, msg);
    }

    @Override
    public void setAdapter(LaunchListResultBean launchListResultBean) {
        if (page == 1) {
            list.clear();
        }
        if (launchListResultBean != null) {
            if (launchListResultBean.data.size() == 0 && page > 1) {
                page--;
            }
            for (LaunchListResultBean.DataBean dataBean : launchListResultBean.data) {
                list.add(dataBean);
            }
        }

        if (adapterLaunch == null) {
            if (!"".equals(flag)) {
                if (list.size() > 0) {
                    SPUtil.putString(this, "appointment_id", list.get(0).appointment_id);
                }
            }

            adapterLaunch = new AdapterLaunch(list);
            adapterLaunch.setOnItemClickListener(this);
            rvLaunchList.setLayoutManager(new LinearLayoutManager(this));
            rvLaunchList.setAdapter(adapterLaunch);
            rvLaunchList.setEmptyView(emptyLaunch);
        }
        adapterLaunch.notifyDataSetChanged();
        rvLaunchList.reSetStatus();
        L.d("WJ", page + "=size=" + launchListResultBean.data.size());
    }

    @Override
    public void updateInfo(AdapterLaunch.MyHolder myHolder, String appointment_id) {
        //更新一下信息 把当前list也更新一下
        for (int i = 0; i < list.size(); i++) {
            LaunchListResultBean.DataBean dataBean = list.get(i);
            if (dataBean.appointment_id.equals(appointment_id)) {
                dataBean.status = "-1";
            }
        }
        myHolder.canCencal = false;
        myHolder.tv_info.setText("您已取消本次约会");
    }

    @Override
    public void onRefresh() {
        //刷新中
        page = 1;
        launchListPresenter.getLaunchList(page, pagenum);
    }

    @Override
    public void onLoadMore() {
        //加载中
        page++;
        launchListPresenter.getLaunchList(page, pagenum);
    }

}
